<template>
  <div class="particle-background">
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const canvas = ref(null)
let ctx = null
let particles = []
let animationFrame = null

class Particle {
  constructor(x, y) {
    this.x = x
    this.y = y
    this.size = Math.random() * 2 + 1
    this.speedX = Math.random() * 2 - 1
    this.speedY = Math.random() * 2 - 1
    this.color = '#30f3f9'
  }

  update() {
    this.x += this.speedX
    this.y += this.speedY

    if (this.size > 0.2) this.size -= 0.01
  }

  draw() {
    ctx.fillStyle = this.color
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
    ctx.fill()
  }
}

function init() {
  const canvas = document.querySelector('canvas')
  ctx = canvas.getContext('2d')
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight

  // 创建初始粒子
  for (let i = 0; i < 100; i++) {
    const x = Math.random() * canvas.width
    const y = Math.random() * canvas.height
    particles.push(new Particle(x, y))
  }
}

function animate() {
  ctx.fillStyle = 'rgba(13, 27, 42, 0.1)'
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)

  for (let i = 0; i < particles.length; i++) {
    particles[i].update()
    particles[i].draw()

    // 连接附近的粒子
    for (let j = i; j < particles.length; j++) {
      const dx = particles[i].x - particles[j].x
      const dy = particles[i].y - particles[j].y
      const distance = Math.sqrt(dx * dx + dy * dy)

      if (distance < 100) {
        ctx.beginPath()
        ctx.strokeStyle = `rgba(48, 243, 249, ${1 - distance/100})`
        ctx.lineWidth = 0.5
        ctx.moveTo(particles[i].x, particles[i].y)
        ctx.lineTo(particles[j].x, particles[j].y)
        ctx.stroke()
      }
    }

    // 重新生成消失的粒子
    if (particles[i].size <= 0.2) {
      particles[i] = new Particle(Math.random() * canvas.value.width, Math.random() * canvas.value.height)
    }
  }

  animationFrame = requestAnimationFrame(animate)
}

onMounted(() => {
  init()
  animate()

  window.addEventListener('resize', () => {
    canvas.value.width = window.innerWidth
    canvas.value.height = window.innerHeight
  })
})

onBeforeUnmount(() => {
  if (animationFrame) {
    cancelAnimationFrame(animationFrame)
  }
})
</script>

<style scoped>
.particle-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: linear-gradient(135deg, #1e4d78 0%, #0c2340 100%);
}

canvas {
  display: block;
}
</style> 